package com.sky.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.demo.VO;
import com.sky.domain.User;
import com.sky.tool.MultipartFileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import sun.management.resources.agent;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 转发/jsp/success.jsp 修改
     * 配置内部资源解析器spring-mvc 修改前缀和后缀
     *
     * @return /jsp/success.jsp
     */
    @RequestMapping(value = {"/quick"})
    public String save() {
        System.out.println("Controller save running...");
        return "success";
    }

    /**
     * 使用视图和模型返回方法
     *
     * @return modelAndView
     */
    @RequestMapping("/quick2")
    public ModelAndView save2() {
        /*
         * 1.model模型 作用封装数据
         * 2.view视图 作用展示数据
         */
        ModelAndView modelAndView = new ModelAndView();
        //设置模型数据
        modelAndView.addObject("username", "big Clever");
        //设置视图名称
        modelAndView.setViewName("success");
        return modelAndView;
    }

    /**
     * 利用mvc封装的modelAndView 添加参数再返回
     *
     * @param modelAndView 请求视图和模型
     * @return modelAndView
     */
    @RequestMapping("/quick3")
    public ModelAndView save3(ModelAndView modelAndView) {
        modelAndView.addObject("username", "clever");
        modelAndView.setViewName("success");
        return modelAndView;
    }

    /**
     * 模型封装
     *
     * @param model 模型
     * @return 转发
     */
    @RequestMapping("/quick4")
    public String save4(Model model) {
        model.addAttribute("username", "dcm");
        return "success";
    }

    @RequestMapping("/quick5")
    public String save5(HttpServletRequest request) {
        HttpSession session = request.getSession();
        request.setAttribute("username", "大聪明的request");
        session.setAttribute("user", "cleverSession");
        return "success";
    }

    @RequestMapping("/write")
    public void give(HttpServletResponse response) throws IOException {
        response.getWriter().print("BIG CLEVER");
    }

    @ResponseBody
    @RequestMapping(value = "/write2", produces = "application/json;charset=utf-8")
    public String give2() {
        return new String("大聪明".getBytes(), StandardCharsets.UTF_8);    //可以不设置编码，没用
    }

    @ResponseBody
    @RequestMapping(value = "/write3", produces = "application/json;charset=utf-8")
    public String give3() {
        return "{username:'dcm',age:'12'}";
    }

    /**
     * 使用ObjectMapper的writeValueAsString将实体类转化为json字符串  导入jackson-core  jackson-annotations  jackson-databind(绑定)
     *
     * @return json字符串
     * @throws JsonProcessingException 转化异常
     */
    @ResponseBody
    @RequestMapping(value = "/write4", produces = "application/json;charset=utf-8")
    public String give4() throws JsonProcessingException {
        User user = new User();
        user.setName("dcm");
        user.setAddr("不知道");
        //使用json转换工具
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(user);
    }

    /**
     * 配置spring-mvc
     * RequestMappingHandlerAdapter.messageConverters = MappingJackson2HttpMessageConverter /
     * <mvc:annotation-driven/> 注解配置
     *
     * @return 实体类
     */
    @ResponseBody
    @RequestMapping(value = "/write5", produces = "application/json;charset=utf-8")
    //SpringMVC自动将user转为json --配置
    public User give5() {
        User user = new User();
        user.setName("dcm");
        user.setAddr("不知道");
        //使用json转换工具
        return user;
    }

    /**
     * 基本类型请求
     *
     * @param name 名字
     * @param age  年龄
     */
    @ResponseBody
    @RequestMapping(value = "/request", produces = "application/json;charset=utf-8")
    public void request(String name, int age) {
        System.out.println("name:" + name);
        System.out.println("age:" + age);
    }

    @ResponseBody
    @RequestMapping(value = "/request2", produces = "application/json;charset=utf-8")
    public void request2(User user) throws JsonProcessingException {
        System.out.println(new ObjectMapper().writeValueAsString(user));
    }

    @ResponseBody
    @RequestMapping(value = "/request3", produces = "application/json;charset=utf-8")
    public void request3(String[] strs) {
        System.out.println(Arrays.asList(strs));
    }

    @ResponseBody
    @RequestMapping(value = "/request4", produces = "application/json;charset=utf-8")
    public void request4(VO vo) {
        System.out.println(vo.toString());
    }

    @ResponseBody
    @RequestMapping(value = "/request5")
    public void request5(@RequestParam(value = "name"
            , defaultValue = "sb") String username) {
        System.out.println(username);
    }

    @ResponseBody
    @RequestMapping(value = "/request6")
    public void request6(Date date) {
        // System.out.println(date);
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
    }

    /**
     * 获取请求头
     *
     * @param user_agent
     */
    @ResponseBody
    @RequestMapping(value = "/request7")
    public void request7(@RequestHeader(value = "User-Agent", required = false) String user_agent) {
        System.out.println(user_agent);
    }

    /**
     * 获取CookieID
     *
     * @param jSessionId
     */
    @ResponseBody
    @RequestMapping(value = "/request8")
    public void request8(@CookieValue(value = "JSESSIONID") String jSessionId) {
        System.out.println(jSessionId);
    }

    /**
     * 单文件上传
     *
     * @param name       用户名
     * @param uploadFile MultipartFile
     * @throws IOException IO
     */
    @ResponseBody
    @RequestMapping(value = "/request9")
    public void request9(@RequestParam("username") String name,
                         @RequestParam("upload") MultipartFile uploadFile) throws IOException {
        System.out.println(name);
        //TODO 获取上传文件名
        MultipartFileUtil.transferTo("D:\\upload\\", uploadFile);
    }


    @ResponseBody
    @RequestMapping(value = "/request10")
    public void request10(@RequestParam("username") String name,
                          @RequestParam("upload") MultipartFile uploadFile,
                          @RequestParam("upload2") MultipartFile uploadFile2) throws IOException {
        System.out.println(name);
        //TODO 获取上传文件名
        MultipartFileUtil.transferTo("D:\\upload\\", uploadFile);
        MultipartFileUtil.transferTo("D:\\upload\\", uploadFile2);
    }

    @ResponseBody
    @RequestMapping(value = "/request11")
    public void request11(@RequestParam("username") String name,
                          @RequestParam("upload") MultipartFile[] uploadFile) throws IOException {
        System.out.println(name);
        //TODO 获取上传文件名
        for (int i = 0, len = uploadFile.length; i < len; i++)
            MultipartFileUtil.transferTo("D:\\upload\\", uploadFile[i]);
    }


    @ResponseBody
    @RequestMapping(value = "/fetch/{id}", method = RequestMethod.GET)
    public void getDynamicUriValue(@PathVariable String id) {
        System.out.println("ID is " + id);
    }

    @RequestMapping(value = "/fetch/{id:[a-z]+}/{name}", method = RequestMethod.GET)
    public String getDynamicUriValueRegex(@PathVariable("name") String name, @PathVariable String id) {
        System.out.println("Name is " + name);
        return "success";
    }


    @RequestMapping(value = "/ajax", produces = "application/json;charset=utf-8")
    @ResponseBody
    public void ajax(@RequestBody List<User> userList) {
        System.out.println(userList);
    }
}
